package com.lin.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lin.reggie.entity.Category;
import com.lin.reggie.service.CategoryService;
import com.lin.reggie.service.impl.CategoryServiceImpl;
import com.lin.reggie.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 菜品及套餐分类 前端控制器
 * </p>
 *
 * @author lin
 * @since 2022-05-26
 */
@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    CategoryService categoryService;

    @Autowired
    CategoryServiceImpl categoryServiceImpl;

    @PostMapping
    public R<String> saveCategory(@RequestBody Category category){

        boolean b = categoryService.save(category);
        if (b=true) {
            return R.success("添加分类成功");
        }
        return R.error("添加失败");
    }


    @GetMapping("/page")
    public R<Page> pageCategory(int page,int pageSize){

        Page pageInfos = new Page(page, pageSize);
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Category::getSort);
        categoryService.page(pageInfos,queryWrapper);
        return R.success(pageInfos);
    }


    @DeleteMapping
    public R<String> deleteCategory(@RequestParam("ids") Long id){

        categoryServiceImpl.removeCategory(id);

        return R.success("删除成功");

    }

    @PutMapping
    public R<String> updateCategory(@RequestBody Category category){

        categoryService.updateById(category);
        return R.success("修改分类成功");
    }

    /*
    根据条件查询分类
    解决添加菜品时的分类下拉框的数据
     */
    @GetMapping("/list")
    public R<List<Category>> list(Category category){

        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        //查询所有分类的类型
        queryWrapper.eq(category.getType() !=null,Category::getType,category.getType());
        //按更新时间排序
        queryWrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        List<Category> list = categoryService.list(queryWrapper);
        return R.success(list);
    }
}

